import {
	ref
} from 'vue';
import {
	useToken
} from './useToken';

export function useWebSocket({
	path = '', 
	params = {}, 
} = {}) {
	const {
		getToken
	} = useToken();
	const ws = ref(null);
	const isConnected = ref(false);
	const messages = ref([]);
	const subscriptions = ref([]);

	let shouldReconnect = true; // 控制是否自动重连

	const connect = () => {
		if (ws.value) return ws.value;

		// 拼接基础地址
		let baseUrl = 'ws://api.flirtyzsex.com/ws';

		if (path) {
			baseUrl += `/${path}`;
		}
		const url = new URL(baseUrl);
		ws.value = new WebSocket(url.toString());

		ws.value.onopen = () => {
			console.log(`✅ WS 已连接: ${url}`);
			isConnected.value = true;

			subscriptions.value.forEach(({
				channel,
				params
			}) => {
				send({
					action: 'subscribe',
					channel,
					params,
				});
			});
		};

		ws.value.onmessage = (e) => {
			try {
				const msg = JSON.parse(e.data);
				messages.value.push(msg);

				// 公共接口才有 channel 订阅机制
				if (msg.channel) {
					subscriptions.value
						.filter((sub) => sub.channel === msg.channel)
						.forEach((sub) => sub.handler?.(msg));
				}
			} catch (err) {
				console.error('❌ WS 消息解析错误', err, e.data);
			}
		};

		ws.value.onerror = (err) => {
			console.error(`❌ WS 错误: ${url}`, err);
		};

		ws.value.onclose = () => {
			console.log(`🔌 WS 已关闭: ${url}`);
			isConnected.value = false;
			ws.value = null;
			// 根据 shouldReconnect 判断是否重连
			if (shouldReconnect) {
				setTimeout(connect, 2000);
			}
		};

		return ws.value;
	};

	// 发送请求
	const send = (data) => {
		if (ws.value && ws.value.readyState === WebSocket.OPEN) {
			ws.value.send(JSON.stringify(data));
		}
	};

	// 订阅公共接口
	const subscribe = (channel, handler, params = {}) => {
		const key = `${channel}:${JSON.stringify(params)}`;
		const exists = subscriptions.value.find((s) => s.key === key);

		if (!exists) {
			subscriptions.value.push({
				key,
				channel,
				handler,
				params,
			});
		} else {
			exists.handler = handler;
			exists.params = params;
		}

		if (isConnected.value) {
			send({
				action: 'subscribe',
				channel,
				params,
			});
		}
	};

	// 销毁或关闭 WebSocket 连接
	const destroy = () => {
		shouldReconnect = false;
		if (ws.value) {
			ws.value.close();
		}
	};

	return {
		connect,
		send,
		subscribe,
		messages,
		isConnected,
		destroy, // 添加销毁方法
	};
}